﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.BLL.Cached;
using ZBJF.Warranty.Common.Common;

namespace ZBJF.Warranty.PinanAPI
{
    public class PinanIdentityService
    {
        public static void RefreshPinanToken()
        {
            var appConfig = ZBJF.Warranty.BLL.Cached.AppConfigCached.GetAppConfig();
            var caller = new WebApiCaller();
            var json =
                caller.Get(
                    string.Format(
                        appConfig.PinanAPIUrl.TrimEnd('/') +
                        "/oauth/oauth2/access_token?client_id={0}&grant_type=client_credentials&client_secret={1}",
                        appConfig.PinanClientID, appConfig.PinanClientSecret), string.Empty);
            CommonMethod.WriteLogs(json);
            var objResult = JSON.JsonToDictionary(json);
            if (objResult!=null && objResult["data"] != null)
            {
                var data = JSON.JsonToDictionary(objResult["data"].ToString());
                if (data != null & data["access_token"] != null)
                {
                    ServiceFactory.AppSettingsServiceInstance.Update("PinanAssessToken", data["access_token"].ToString(),
                        DateTime.Now.ToString(CultureInfo.InvariantCulture));
                }
            }
        }
    }
}
